package ru.btabank.dom.xpath.expression;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import ru.btabank.dom.util.DOMUtil;
import ru.btabank.dom.xpath.XPathException;

public class AttributeStep extends NameStep {

    public AttributeStep(String prefix, String localName, String namespaceURI) {
        super(prefix, localName, namespaceURI);
    }

    public NodeSet select(NodeSet source) {
        NodeSet target;
        Node sourceNode, atributeNode;
        NamedNodeMap attributeNodes;

        target = new NodeSet();
        for (int sourceIndex = 0; sourceIndex < source.getLength(); sourceIndex++) {
            sourceNode = source.item(sourceIndex);
            attributeNodes = sourceNode.getAttributes();
            for (int attributeIndex = 0; attributeIndex < attributeNodes.getLength(); attributeIndex++) {
                atributeNode = attributeNodes.item(attributeIndex);
                if (super.matches(atributeNode)) {
                    target.add(atributeNode);
                }
            }
        }
        return target;
    }

    public NodeSet build(NodeSet source) throws XPathException {
        NodeSet target, temp;
        Node sourceNode, atributeNode;
        NamedNodeMap attributeNodes;

        target = new NodeSet();
        temp = new NodeSet();
        for (int sourceIndex = 0; sourceIndex < source.getLength(); sourceIndex++) {
            sourceNode = source.item(sourceIndex);
            attributeNodes = sourceNode.getAttributes();
            for (int attributeIndex = 0; attributeIndex < attributeNodes.getLength(); attributeIndex++) {
                atributeNode = attributeNodes.item(attributeIndex);
                if (super.matches(atributeNode)) {
                    temp.add(atributeNode);
                }
            }
            if (temp.getLength() == 0) {
                atributeNode = DOMUtil.createAttribute(sourceNode, super.getName(), super.getNamespaceURI());
                temp.add(atributeNode);
            }
            target.add(temp);
            temp.clear();
        }
        return target;
    }

    public String toString() {
        return "@" + super.getName();
    }
}
